package com.zytlifeservice.service.pay;

import com.qianmi.open.api.ApiException;
import com.qianmi.open.api.domain.elife.PhoneInfo;
import com.qianmi.open.api.request.BmMobileFlowItemsList2Request;
import com.qianmi.open.api.request.BmMobileFlowPayBillRequest;
import com.qianmi.open.api.request.BmRechargeMobileGetPhoneInfoRequest;
import com.qianmi.open.api.response.BmMobileFlowItemsList2Response;
import com.qianmi.open.api.response.BmMobileFlowPayBillResponse;
import com.qianmi.open.api.response.BmRechargeMobileGetPhoneInfoResponse;
import com.zytlifeservice.domain.Result;
import com.zytlifeservice.domain.User;
import com.zytlifeservice.domain.pay.AlipayOrder;
import com.zytlifeservice.domain.pay.BaseQmOrder;
import com.zytlifeservice.domain.pay.FlowRechargeOrder;
import com.zytlifeservice.domain.pay.WxPayOrder;
import com.zytlifeservice.exception.UserException;
import com.zytlifeservice.repository.UserRepository;
import com.zytlifeservice.repository.pay.AlipayOrderRepository;
import com.zytlifeservice.repository.pay.FlowRechargeOrderRepository;
import com.zytlifeservice.repository.pay.WxPayOrderRepository;
import com.zytlifeservice.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 手机流量业务类
 * Created by Administrator on 2017/6/3.
 */
@Service
public class FlowRechargeOrderService {
    private static final Logger logger = LoggerFactory.getLogger(FlowRechargeOrderService.class);

    @Autowired
    private FlowRechargeOrderRepository flowRechargeOrderRepository;//手机流量持久对象

    @Autowired
    private AlipayOrderRepository alipayOrderRepository;

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    WxPayOrderRepository wxPayOrderRepository;

    @Autowired
    PublicService publicService;

    @Autowired
    WxPayService wxPayService;

    @Autowired
    private MoblieAndFlowCostService moblieAndFlowCostService;

    //手机流量直充
    public String[] createOrder(String mobileNo, String rechargeAmount, String flow, Long userId) throws ApiException {
        User one = userRepository.findOne(userId);
        if (one == null) {
            throw new UserException("用户不存在", 104);
        }
        String[] res = new String[2];
        BmMobileFlowItemsList2Request req = new BmMobileFlowItemsList2Request();
        req.setMobileNo(mobileNo);
        req.setFlow(flow);
        BmMobileFlowItemsList2Response response = publicService.execute(req);
        if (!response.isSuccess()) {
            res[0] = "fail";
            res[1] = response.getSubMsg();
            return res;
        }
        response.getItems().get(0).getItemName();
        AlipayOrder alipayOrder = new AlipayOrder();
        alipayOrder.setStoreId(one.getStoreId());
        alipayOrder.setSubject(response.getItems().get(0).getItemName());//对应的后台的信息
        String outTradeNo = "zyt" + userId + System.currentTimeMillis()   //添加userId
                + (long) (Math.random() * 10000000L);
        alipayOrder.setOutTradeNo(outTradeNo);
        alipayOrder.setTotalAmount(rechargeAmount);
        alipayOrder.setUserId(userId);
        alipayOrder.setType(AlipayOrder.TYPE_MOBILE_FLOW);
        alipayOrderRepository.save(alipayOrder);

        //同时，这里要生成千米的订单
        FlowRechargeOrder flowRechargeOrder = new FlowRechargeOrder();
        publicService.setBaseOrderType(flowRechargeOrder);
        flowRechargeOrder.setRechargeAccount(mobileNo);
        flowRechargeOrder.setItemId(response.getItems().get(0).getItemId());
        flowRechargeOrder.setOutTradeNo(outTradeNo);
        flowRechargeOrder.setItemName(response.getItems().get(0).getItemName());
        flowRechargeOrder.setUserId(userId);
        flowRechargeOrder.setPayType(BaseQmOrder.PAY_TYPE_ALIPAY);
        flowRechargeOrder.setFaceValue(flow);
        flowRechargeOrder.setSaleAmount(response.getItems().get(0).getAdvicePrice());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        flowRechargeOrder.setOrderTime(sdf.format(new Date()));
        flowRechargeOrder.setPayState("0");  //这里修改其状态。

        flowRechargeOrder.setPayResult(BaseQmOrder.STATUS_INIT);
        if (!publicService.querySum(rechargeAmount)) {
            flowRechargeOrder.setFailReason("直销商余额不足,取消支付宝预下单");
            flowRechargeOrderRepository.save(flowRechargeOrder);
            res[0] = "fail";
            res[1] = "直销商余额不足,取消支付宝预下单";
            return res;
        }
        flowRechargeOrderRepository.save(flowRechargeOrder);
        res[0] = "success";
        res[1] = alipayService.pay(alipayOrder) + "," + outTradeNo;
        return res;
    }


    public String[] wxPreCreate(String mobileNo, String rechargeAmount, String flow, Long userId, String ip) throws ApiException {
        User one = userRepository.findOne(userId);
        if (one == null) {
            throw new UserException("用户不存在", 104);
        }
        String[] res = new String[2];
        BmMobileFlowItemsList2Request req = new BmMobileFlowItemsList2Request();
        req.setMobileNo(mobileNo);
        req.setFlow(flow);
        BmMobileFlowItemsList2Response response = publicService.execute(req);
        if (!response.isSuccess()) {
            res[0] = "fail";
            res[1] = response.getSubMsg();
            return res;
        }

        String outTradeNo = "zyt" + userId + System.currentTimeMillis()   //添加userId
                + (long) (Math.random() * 10000000L);
        WxPayOrder wxPayOrder = publicService.generateWxpayOrder(one, response.getItems().get(0).getItemName(), ip,
                rechargeAmount, outTradeNo, WxPayOrder.TYPE_MOBILE_FLOW);
        wxPayOrderRepository.save(wxPayOrder);

        FlowRechargeOrder flowRechargeOrder = new FlowRechargeOrder();
        publicService.setBaseOrderType(flowRechargeOrder);
        flowRechargeOrder.setRechargeAccount(mobileNo);
        flowRechargeOrder.setItemId(response.getItems().get(0).getItemId());
        flowRechargeOrder.setOutTradeNo(outTradeNo);
        flowRechargeOrder.setItemName(response.getItems().get(0).getItemName());
        flowRechargeOrder.setUserId(userId);
        flowRechargeOrder.setFaceValue(flow);
        flowRechargeOrder.setPayType(BaseQmOrder.PAY_TYPE_WXPAY);
        flowRechargeOrder.setSaleAmount(response.getItems().get(0).getAdvicePrice());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        flowRechargeOrder.setOrderTime(sdf.format(new Date()));
        flowRechargeOrder.setPayState("0");  //这里修改其状态。

        flowRechargeOrder.setPayResult(BaseQmOrder.STATUS_INIT);
        if (!publicService.querySum(rechargeAmount)) {
            flowRechargeOrder.setFailReason("直销商余额不足,取消支付宝预下单");
            flowRechargeOrderRepository.save(flowRechargeOrder);
            res[0] = "fail";
            res[1] = "直销商余额不足,取消支付宝预下单";
            return res;
        }
        flowRechargeOrderRepository.save(flowRechargeOrder);
        res[0] = "success";
        res[1] = wxPayService.pay(wxPayOrder) + "," + outTradeNo;
        return res;
    }

    //查询单个手机流量商品
    public Result flowSend(String mobile, String flow) throws Exception {
        BmMobileFlowItemsList2Request req = new BmMobileFlowItemsList2Request();
        req.setMobileNo(mobile);
        req.setFlow(flow);
        BmMobileFlowItemsList2Response response = publicService.execute(req);
        if (response.getItems() != null && response.getItems().size() > 0) {
            return ResultUtil.success(response.getItems().get(0).getItemId(), "查询成功");
        } else {
            return ResultUtil.error(303, "查询失败");
        }
    }

    //这里要得到千米的订单信息。执行消费。
    public String payFlowChargeOrder(String outTradeNo) {
        FlowRechargeOrder flowRechargeOrder = flowRechargeOrderRepository.findByOutTradeNo(outTradeNo);
        logger.error("查询的order:{}", flowRechargeOrder);
        BmMobileFlowPayBillRequest req = new BmMobileFlowPayBillRequest();
        req.setItemId(flowRechargeOrder.getItemId());
        req.setOuterTid(flowRechargeOrder.getOutTradeNo());
        req.setMobileNo(flowRechargeOrder.getRechargeAccount());
        req.setCallback(publicService.getBmCallbackUrl());
        try {
            BmMobileFlowPayBillResponse response = publicService.execute(req);
            logger.error("支付状态:{}", response.isSuccess());
            logger.error("支付结果body:{}", response.getBody());
            if (!response.isSuccess()) {
                //处理错误
                //记录错误原因，同时，执行支付宝退款流程。
                flowRechargeOrder.setFailReason(response.getSubMsg());
                flowRechargeOrder.setPayResult(BaseQmOrder.STATUS_FAIL);
                flowRechargeOrderRepository.save(flowRechargeOrder);

                if (flowRechargeOrder.getPayType() == BaseQmOrder.PAY_TYPE_ALIPAY) {
                    AlipayOrder byOutTradeNo = alipayOrderRepository.findByOutTradeNo(outTradeNo);
                    byOutTradeNo.setRefundReason(response.getSubMsg());
                    return alipayService.reFund(byOutTradeNo);
                } else if (flowRechargeOrder.getPayType() == BaseQmOrder.PAY_TYPE_WXPAY) {
                    WxPayOrder wxPayOrder = wxPayOrderRepository.findByOutTradeNo(outTradeNo);
                    wxPayOrder.setRefundReason(response.getSubMsg());
                    return wxPayService.refund(wxPayOrder);
                }
            }
            publicService.parseResponse(flowRechargeOrder, response.getOrderDetailInfo());
            flowRechargeOrderRepository.save(flowRechargeOrder);
        } catch (ApiException e) {
            flowRechargeOrder.setFailReason(e.getMessage());
            flowRechargeOrder.setPayResult(BaseQmOrder.STATUS_FAIL);
            flowRechargeOrderRepository.save(flowRechargeOrder);
            if (flowRechargeOrder.getPayType() == BaseQmOrder.PAY_TYPE_ALIPAY) {
                AlipayOrder byOutTradeNo = alipayOrderRepository.findByOutTradeNo(outTradeNo);
                byOutTradeNo.setRefundReason(e.getMessage());
                return alipayService.reFund(byOutTradeNo);
            } else if (flowRechargeOrder.getPayType() == BaseQmOrder.PAY_TYPE_WXPAY) {
                WxPayOrder wxPayOrder = wxPayOrderRepository.findByOutTradeNo(outTradeNo);
                wxPayOrder.setRefundReason(e.getMessage());
                return wxPayService.refund(wxPayOrder);
            }
            e.printStackTrace();
            throw new UserException("付款失败", 202);  //付款失败，走退款流程
        }
        return "error";
    }


    public PhoneInfo queryPhoneInfo(String mobile) {
        BmRechargeMobileGetPhoneInfoRequest request = new BmRechargeMobileGetPhoneInfoRequest();
        request.setPhoneNo(mobile);
        try {
            BmRechargeMobileGetPhoneInfoResponse response = publicService.execute(request);
            if (response.isSuccess()) {
                return response.getPhoneInfo();
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        throw new UserException("查询失败", 303);
    }
}
